package be.jhd.repository;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;


public class Downloader {

	private final UrlBuilder urlBuilder;

	public Downloader(UrlBuilder urlBuilder){
		this.urlBuilder = urlBuilder;
	}
	
	public byte[] download(Artifact artifact) throws DownloadException{
		final String url = urlBuilder.buildUrl(artifact);
		final HttpMethod method = new GetMethod(url);
		final HttpClient client = new HttpClient();
		
		try{
			final int statusCode = client.executeMethod(method);
			checkStatusCodeOK(statusCode);
			return method.getResponseBody();
		}catch(Exception exc){
			throw new DownloadException(artifact, url, exc);
		}finally{
			method.releaseConnection();
		}
	}

	private void checkStatusCodeOK(int statusCode) {
		if(statusCode != HttpStatus.SC_OK){
			throw new RuntimeException("bad status code: " + statusCode);
		}
	}
	
	
	
}
